package lowijs.XfDroid;

import static lowijs.XfDroid.XfDroidConstants.*;

import com.googlecode.xfdroid.R;
import lowijs.XfireClient.XfireObserver;
import lowijs.XfireClient.event.EventManager;
import lowijs.XfireClient.event.XfireEvent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ReconnectActivity extends Activity implements XfireObserver {
	public static final int CODE = 101;

	private Handler handler;

	public void onCreate(Bundle b) {
		super.onCreate(b);
		setContentView(R.layout.reconnect);

		Button cancel = (Button)findViewById(R.id.Cancel);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				updateStatus();
			}
		};

		cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				XfDroidService.stopReconnect();
			}
		});
	}

	class Watcher extends Thread {
		public void run() {
            while (XfDroidService.isReconnecting()) {
                Message m = new Message();
                m.what = ReconnectActivity.CODE; 
            	handler.sendMessage(m);
            	try {
            		Thread.sleep(500);
            	} catch (Exception e) {
            	}
			}
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		updateStatus();
		EventManager.addObserver(this);
		new Watcher().start();
	}

	@Override
	protected void onStop() {
		super.onStop();
		EventManager.removeObserver(this);
	}

	public void handleEvent(XfireEvent event) {
		switch(event.getEventType()) {
		case XfireEvent.XF_DCREASON:
		case XfireEvent.XF_OFFLINE:
			startActivity(new Intent(this, Login.class));
			finish();
			return;
		case XfireEvent.XF_RECONNECTED:
			startActivity(new Intent(this, Friendslist.class));
			finish();
			return;
		}
	}

	private void updateStatus() {
		TextView status = (TextView)findViewById(R.id.Status);
		String text = getString(R.string.reconnect);
		text = text.replace(ARG_0, Integer.toString(XfDroidService.getReconnectTime() / 1000));
		status.setText(text);
	}
}
